package jaux.tank.generator.jd.components;

import java.util.Arrays;
import java.util.function.Consumer;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JComponent;

import lombok.extern.slf4j.Slf4j;
@Slf4j
public class JdComboBox<E> extends JdLabeledInput<E, E[]> {
	private static final long serialVersionUID = 1L;

	private JComboBox<E> comboBox;

	public JdComboBox(String label, E[] items) {
		this(label, null, items);

	}

	public JdComboBox(String label, E defaultValue, E[] items) {
		super(label, defaultValue, items);

	}

	@SuppressWarnings("unchecked")
	@Override
	public E getValue() {
		return (E) this.comboBox.getSelectedItem();
	}

	@Override
	public void setValue(E value) {
		this.comboBox.setSelectedItem(value);
	}

	@Override
	public void setEditable(boolean b) {
		this.comboBox.setEnabled(b);	
	}
	@Override
	public JComponent createInputComponent(E[] params) {
		comboBox = new JComboBox<>();
		comboBox.setEditable(false);
		if(params !=null) {
			
			for (E item : params) {
				this.comboBox.addItem(item);
			}
		}
		return comboBox;
	}

	@Override
	protected void registerChangeHandler(Consumer<E> handler) {
		comboBox.addActionListener(e ->{
			log.debug("value changed: {}", getValue());
			handler.accept(getValue());
		});
		
	}

	public E setListData(E[] items) {
		E currentValue =getValue();
		DefaultComboBoxModel<E> aModel = new DefaultComboBoxModel<>(items);
		if(items!=null && currentValue!=null &&Arrays.asList(items).contains(currentValue)) {
			aModel.setSelectedItem(currentValue);
		}else {
			aModel.setSelectedItem(null);
		}
		comboBox.setModel(aModel);
		return currentValue;
	}
}
